import axios from "axios";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css";
import { ElMessage } from "element-plus";
import { getToken } from "@/utils/local";
const baseUrl = import.meta.env.VITE_VUE_APP_BASE_URL;
console.log('baseUrl----------',import.meta.env)
axios.defaults.withCredentials = true;
axios.defaults.baseURL = baseUrl;
NProgress.configure({
    showSpinner: false,
});

// HTTPrequest拦截  
axios.interceptors.request.use(
    (config) => {
        if (getToken()) config.headers["Authorization"] = "Bearer " + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
        NProgress.start(); // start progress bar
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);
// HTTPresponse拦截
axios.interceptors.response.use(
    (res) => {
        NProgress.done();
        let status = Number(res.status) || 200;
        let msg = res.data.msg || "服务端错误";
        if (status !== 200 || res.data.code === 0 || res.data.code === 401) {
            ElMessage({ message: msg, type: "error" });
            return Promise.reject(new Error(msg));
        }
        return Promise.resolve(res.data);
    },
    (error) => {
        NProgress.done();
        return Promise.reject(new Error(error));
    }
);

export default axios;
